/*
 * @Author: WangLi
 * @Date: 2021-07-16 09:49:36
 * @LastEditors: WangLi
 * @LastEditTime: 2024-05-19 06:25:52
 * @Description:
 */
import { getSystemInfoSync } from "./utils/util";
import { getUser, setUser } from "./utils/storage";

App({
  globalData: {},
  async onLaunch(options) {
    this.update();
    const { statusBarHeight, windowWidth, safeArea, screenHeight, pixelRatio } = getSystemInfoSync();
    this.globalData.windowWidth = windowWidth;
    this.globalData.pixelRatio = pixelRatio;
    this.globalData.isSafe = safeArea.bottom < screenHeight;
    if (wx.getMenuButtonBoundingClientRect) {
      const { top, right, height, left } = wx.getMenuButtonBoundingClientRect();
      this.globalData.statusBarHeight = statusBarHeight;
      this.globalData.titlePadding = windowWidth - left + 10;
      this.globalData.navbarHeight = statusBarHeight + height + (top - statusBarHeight) * 2;
    }
    this.globalData.preview = false;
    const userInfo = getUser();
    if (userInfo?.openid) {
      return;
    }
    this.initCloud();
    this.getOpenId();
  },
  update() {
    const updateManager = wx.getUpdateManager();

    updateManager.onCheckForUpdate(function (res) {
      // 请求完新版本信息的回调
      console.log(res.hasUpdate);
    });

    updateManager.onUpdateReady(function () {
      wx.showModal({
        title: "更新提示",
        content: "新版本已经准备好，是否重启应用？",
        success: function (res) {
          if (res.confirm) {
            // 新的版本已经下载好，调用 applyUpdate 应用新版本并重启
            updateManager.applyUpdate();
          }
        },
      });
    });

    updateManager.onUpdateFailed(function () {
      // 新版本下载失败
    });
  },
  initCloud() {
    wx.cloud.init({
      // env 参数决定接下来小程序发起的云开发调用（wx.cloud.xxx）会默认请求到哪个云环境的资源
      env: "btkey-2gup5ah0fb82a9c0",
      // 是否在将用户访问记录到用户管理中，在控制台中可见，默认为false
      traceUser: false,
    });
  },
  getOpenId() {
    wx.cloud
      .callFunction({
        name: "quickstartFunctions",
        config: {
          env: "btkey-2gup5ah0fb82a9c0",
        },
        data: {
          type: "getOpenId",
        },
      })
      .then((res) => {
        console.log(res);
        setUser(res.result);
      })
      .catch((e) => {});
  },
});
